/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.infra.topic;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import edu.cmu.lti.sepia.data.xml.IXmlHandler;
import edu.cmu.lti.sepia.data.xml.IXmlSerializable;
import edu.cmu.lti.sepia.infra.topic.model.Topic;
import edu.cmu.lti.sepia.infra.topic.model.TopicSet;

public class GoldStandardXmlFacade {
  
  public static TopicSet deserializeTopicSet( InputStream is, String srcLang, String trgLang ) {
    IXmlSerializable result = null;
    IXmlHandler handler = new GoldStandardXmlToObj(srcLang,trgLang);
    try {
      XMLReader xmlReader = XMLReaderFactory.createXMLReader();
      xmlReader.setContentHandler(handler);
      xmlReader.parse(new InputSource(is));
      result = handler.getParsed();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return (TopicSet)result;
  }

  public static TopicSet deserializeTopicSet( String xml, String srcLang, String trgLang ) {
    ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes());
    return deserializeTopicSet(is, srcLang, trgLang);
  }
  
  public static String serializeTopicSet( TopicSet resultSet ) {
    String srcLang = resultSet.getSourceLanguage();
    String trgLang = resultSet.getTargetLanguage();
    String desc = resultSet.getMetadata().get("DESCRIPTION");
    List<Topic> topics = new ArrayList<Topic>( resultSet.values() );
    return GoldStandardObjToXml.toGoldStandardXml(topics, srcLang, trgLang, desc);
  }
  
  
}
